using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using MedicalReportAssistant.Controllers;
using Microsoft.Extensions.Logging;

namespace MedicalReportAssistant.Views
{
    public partial class FloatingWindow : Window
    {
        private readonly MedicalReportController _controller;
        private readonly ILogger<FloatingWindow> _logger;
        private IntPtr _windowHandle;

        public FloatingWindow(MedicalReportController controller, ILogger<FloatingWindow> logger)
        {
            InitializeComponent();
            _controller = controller;
            _logger = logger;
            DataContext = controller;

            // 设置窗口初始位置
            SetInitialPosition();

            // 注册窗口加载事件
            this.Loaded += FloatingWindow_Loaded;
        }

        private void FloatingWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                // 获取窗口句柄
                _windowHandle = new WindowInteropHelper(this).Handle;
                if (_windowHandle == IntPtr.Zero)
                {
                    System.Windows.Application.Current.Dispatcher.Invoke(() =>
                    {
                        Views.LogWindow.Instance.LogError("无法获取窗口句柄");
                    });
                    return;
                }

                // 设置窗口样式
                SetWindowStyle();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "设置窗口样式失败");
            }
        }

        private void SetInitialPosition()
        {
            var screenWidth = SystemParameters.PrimaryScreenWidth;
            var screenHeight = SystemParameters.PrimaryScreenHeight;
            
            Left = screenWidth - Width - 20;
            Top = screenHeight - Height - 40;
        }

        private void SetWindowStyle()
        {
            try
            {
                if (_windowHandle == IntPtr.Zero)
                {
                    System.Windows.Application.Current.Dispatcher.Invoke(() =>
                    {
                        Views.LogWindow.Instance.LogError("窗口句柄无效");
                    });
                    return;
                }

                // 设置窗口扩展样式
                var extendedStyle = GetWindowLong(_windowHandle, GWL_EXSTYLE);
                if (extendedStyle == 0)
                {
                    var error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                    System.Windows.Application.Current.Dispatcher.Invoke(() =>
                    {
                        Views.LogWindow.Instance.LogError($"获取窗口样式失败: Win32错误码 {error}");
                    });
                    return;
                }

                // 添加置顶标志
                var newStyle = extendedStyle | WS_EX_TOPMOST;
                var result = SetWindowLong(_windowHandle, GWL_EXSTYLE, newStyle);
                if (result == 0)
                {
                    var error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                    System.Windows.Application.Current.Dispatcher.Invoke(() =>
                    {
                        Views.LogWindow.Instance.LogError($"设置窗口样式失败: Win32错误码 {error}");
                    });
                    return;
                }

                System.Windows.Application.Current.Dispatcher.Invoke(() =>
                {
                    Views.LogWindow.Instance.LogInfo("窗口样式设置成功");
                });
            }
            catch (Exception ex)
            {
                System.Windows.Application.Current.Dispatcher.Invoke(() =>
                {
                    Views.LogWindow.Instance.LogError($"设置窗口样式时发生异常: {ex.Message}");
                });
            }
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    DragMove();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "拖动窗口失败");
            }
        }

        private void MinimizeButton_Click(object sender, RoutedEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        // Win32 API 声明
        private const int GWL_EXSTYLE = -20;
        private const int WS_EX_TOPMOST = 0x0008;

        [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
        private static extern int GetWindowLong(IntPtr hWnd, int nIndex);

        [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
        private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
    }
} 